package com.sky.service.admin.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2024/10/10 11:44
 * @Version 1.0
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        //本质：存两张表，1.dish  2.dish_flavor
        //先存dish表，然后获得dish表的id赋值给flavor里面
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.DISABLE);

        dishMapper.insert(dish);
        //保存口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(!CollectionUtils.isEmpty(flavors)){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        //1.修改菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //2.修改口味,做法：先删除，再重新插入即可
        dishFlavorMapper.deleteByDishIds(Arrays.asList(dishDTO.getId()));
        //保存口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(!CollectionUtils.isEmpty(flavors)){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insertBatch(flavors);
        }
        cleanCache();
    }

    private void cleanCache(){
        Set keys = redisTemplate.keys(RedisConstant.CATEGORY_CACHE_PREFIX + "*");
        redisTemplate.delete(keys);
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dto) {
        dto.check();
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dto);

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        //先去查询，如果有起售状态的菜品，就不删
        List<Dish> dishes = dishMapper.queryOnSaleDishByIds(ids);
        if(!CollectionUtils.isEmpty(dishes)){
            throw new BaseException("包含售卖中的菜品");
        }
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    @Override
    public DishVO getDishById(Long id) {
        DishVO dishVO = dishMapper.getDishById(id);
        dishVO.setFlavors(dishFlavorMapper.getFlavorByDishId(id));
        return dishVO;
    }

    /**
     * 条件查询菜品和口味
     * @param categoryId
     * @return
     */
    public List<DishVO> listWithFlavor(Integer categoryId) {
        //key一定要加业务前缀     category:12
        String key = RedisConstant.CATEGORY_CACHE_PREFIX + categoryId;
        String dishJson = (String)redisTemplate.opsForValue().get(key);
        if(StringUtils.hasText(dishJson)){
            log.info("从缓存查询,categoryId:{}",categoryId);
            return JSONObject.parseArray(dishJson,DishVO.class);
        }

        List<Dish> dishList = dishMapper.getDishByCategoryId(categoryId);

        List<DishVO> dishVOList = new ArrayList<>();
        //批量查询索引菜品的口味
        List<Long> dishIds = dishList.stream().map(Dish::getId).collect(Collectors.toList());
        List<DishFlavor> dishFlavors = dishFlavorMapper.getFlavorByDishIds(dishIds);

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            List<DishFlavor> flavors = dishFlavors.stream().filter(f -> f.getDishId().equals(d.getId())).collect(Collectors.toList());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList));

        return dishVOList;
    }
}